﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Ledict.Utility.Common
{
    public class Other
    {
        /// <summary>  
        /// 获取当前使用的IP  
        /// </summary>  
        /// <returns></returns>  
        public static string GetLocalIP()
        {
            string result = RunApp("route", "print", true);
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
            if (m.Success)
            {
                return m.Groups[2].Value;
            }
            else
            {
                try
                {
                    System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
                    c.Connect("www.baidu.com", 80);
                    string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                    c.Close();
                    return ip;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
        }

        /// <summary>  
        /// 运行一个控制台程序并返回其输出参数。  
        /// </summary>  
        /// <param name="filename">程序名</param>  
        /// <param name="arguments">输入参数</param>  
        /// <returns></returns>  
        public static string RunApp(string filename, string arguments, bool recordLog)
        {
            try
            {
                if (recordLog)
                {
                    System.Diagnostics.Trace.WriteLine(filename + " " + arguments);
                }
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = filename;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.Arguments = arguments;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.UseShellExecute = false;
                proc.Start();

                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
                {
                    //string txt = sr.ReadToEnd();  
                    //sr.Close();  
                    //if (recordLog)  
                    //{  
                    //    Trace.WriteLine(txt);  
                    //}  
                    //if (!proc.HasExited)  
                    //{  
                    //    proc.Kill();  
                    //}  
                    //上面标记的是原文，下面是我自己调试错误后自行修改的  
                    System.Threading.Thread.Sleep(100);           //貌似调用系统的nslookup还未返回数据或者数据未编码完成，程序就已经跳过直接执行  
                                                 //txt = sr.ReadToEnd()了，导致返回的数据为空，故睡眠令硬件反应  
                    if (!proc.HasExited)         //在无参数调用nslookup后，可以继续输入命令继续操作，如果进程未停止就直接执行  
                    {                            //txt = sr.ReadToEnd()程序就在等待输入，而且又无法输入，直接掐住无法继续运行  
                        proc.Kill();
                    }
                    string txt = sr.ReadToEnd();
                    sr.Close();
                    if (recordLog)
                        System.Diagnostics.Trace.WriteLine(txt);
                    return txt;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
                return ex.Message;
            }
        }


        /// <summary>
        /// 通过正常方式获取IPV4地址
        /// </summary>
        /// <returns></returns>
        public static string GetIPNormal()
        {
            string st = string.Empty;
            string name = System.Net.Dns.GetHostName();
            System.Net.IPAddress[] ipadrlist = System.Net.Dns.GetHostAddresses(name);
            foreach (System.Net.IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    st = ipa.ToString();
                }
            }
            return st;
        }
        public static string GetIpAddress()
        {
            try
            {
                string ipAddress = string.Empty;
                string hostName = Dns.GetHostName();   //获取本机名
                                                       //IPHostEntry localhost = Dns.GetHostByName(hostName);    //方法已过期，可以获取IPv4的地址
                IPHostEntry localhost = Dns.GetHostEntry(hostName);   //获取IPv6地址
                foreach (IPAddress str in localhost.AddressList)
                {
                    if (str.Address.ToString().StartsWith("192"))
                    {
                        ipAddress= str.Address.ToString();
                    }
                    else
                    {
                        ipAddress= localhost.AddressList[0].ToString();
                    }
                }
                return ipAddress;
            }
            catch (Exception ex)
            {
                return "";
            }
            //IPAddress localaddr = localhost.AddressList[0];
            //if(lo)
            //return localaddr.ToString();
        }
    }
}
